package com.kusej.idno.generation.utils;

import java.util.Random;

public class IDCardUtils {
    public static void main(String[] args) {
        String regionCode = "372923"; // 区域代码，以北京市东城区为例
        String birthDate = "19900125"; // 出生年月日，8位格式的年月日
        boolean isMale = true; // 性别，true为男性，false为女性
        int n = 5; // 要生成的身份证号码个数

        for (int i = 0; i < n; i++) {
            String idCardNumber = generateIDCardNumber(regionCode, birthDate, isMale);
            System.out.println(idCardNumber);
        }
    }

    public static String generateIDCardNumber(String regionCode, String birthDate, boolean isMale) {
        StringBuilder idCardNumber = new StringBuilder();

        // 添加区域代码
        idCardNumber.append(regionCode);

        // 添加出生年月日
        idCardNumber.append(birthDate);

        // 添加顺序码
        Random random = new Random();
        int sequenceCode = random.nextInt(1000);
        idCardNumber.append(String.format("%03d", sequenceCode));


        // 根据性别调整最后一位数字
        int lastDigit = Integer.parseInt(idCardNumber.substring(16, 17));
        if (isMale) {
            lastDigit = lastDigit % 2 == 0 ? lastDigit - 1 : lastDigit;
        }else{
            lastDigit = lastDigit % 2 == 0 ? lastDigit : lastDigit - 1;
        }
        idCardNumber.replace(16, 17, String.valueOf(Math.abs(lastDigit)));

        // 添加校验码
        idCardNumber.append(getCheckCode(idCardNumber.toString()));

        return idCardNumber.toString();
    }

    public static String getCheckCode(String idCardNumber) {
        int[] coefficients = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
        String[] checkCodes = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            int digit = Integer.parseInt(idCardNumber.substring(i, i + 1));
            sum += digit * coefficients[i];
        }
        int checkCodeIndex = sum % 11;
        return checkCodes[checkCodeIndex];
    }
}
